<template lang="">
  <div class="cart">
    <van-nav-bar title="购物车" />

    <div class="list">
      <van-card
        v-for="item in cartListArr"
        :key="item.cartid"
        :num="item.num"
        :price="item.originprice"
        :title="item.proname"
        :thumb="item.img1"
      >
        <template #footer>
          <van-checkbox class="ck" v-model="item.flag" @click="selectOne(item)"></van-checkbox>
          <van-stepper v-model="item.num" integer min="1" @change="unpdateNum(item)" />
          <van-button type="danger" size="mini" @click="removeOne(item)">删除</van-button>
        </template>
      </van-card>
    </div>

    <van-submit-bar :price="cartAllPrice" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="isCheckedAll" @click="changeSelectAll" :disabled="isdis"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </div>
</template>
<script lang="ts" setup>
import { cartList, cartRemoveOne, cartSelectOne, cartSelectAll, cartUpdateNum } from '@/api/cart'
import { ref, watchEffect } from 'vue'

import { useUser } from '@/stores/user'
let user = useUser()

function onSubmit() {}

loadCartList()

// 获取购物车列表
let cartListArr = ref([])
function loadCartList() {
  cartList().then((r) => {
    cartListArr.value = r.data
    user.cartNum =cartListArr.value.length
    if (!cartListArr.value) {
      isdis.value = true
    }
  })
}

//更改购物车数量
async function unpdateNum(item) {
  let r = await cartUpdateNum(item.cartid, item.num)
}

//删除购物车单条数据
const isCheckedAll = ref(false)
async function removeOne(item) {
  let r = await cartRemoveOne(item.cartid)
  loadCartList()
}

//所有数据选中状态
let isdis = ref(false)
async function changeSelectAll() {
  if (cartListArr.value) {
    let r = await cartSelectAll(isCheckedAll.value)
    cartListArr.value.forEach((item) => {
      item.flag = isCheckedAll.value
    })
  } else isdis.value = true
}

//单条数据选中状态
async function selectOne(item) {
  let r = await cartSelectOne(item.cartid, item.flag)
  loadCartList()
}

//选中商品价格
let cartAllPrice = ref(0)
watchEffect(function () {
  if (cartListArr.value) {
    isCheckedAll.value = cartListArr.value.every((v) => v.flag == true)
    cartAllPrice.value = cartListArr.value
      .filter((v) => (v.flag as boolean) == true)
      .reduce((sum, i) => sum + i.originprice * i.num * 100, 0)
    user.cartNum = cartListArr.value.length
  } else {
    isCheckedAll.value = false
    cartAllPrice.value = 0
  }
})
</script>

<style lang="scss" scoped>
.cart {
  height: 100%;
  display: flex;
  flex-direction: column;

  .list {
    flex: 1;
    overflow-y: scroll;
  }
  .van-submit-bar {
    position: static;
  }
}

/* 修改 card内部的一些样式 */
:deep .van-card__footer {
  display: flex;
  justify-content: right;
  margin-top: 20px;
}
:deep .van-card__header {
  margin-left: 50px;
}
.van-card {
  position: relative;
}
.ck {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
}
.van-stepper {
  margin-left: 50px;
}
</style>
